import types
import sys
try:
	import readline
except:
	print "Print Install GNU Readline interface"
	sys.exit()

import includes.db as db
import includes.asp_wrapper as wrapper
import includes.http as http

global debug
global managers

def init(init_debug, init_managers):
	global debug
	global managers
	debug=init_debug
	managers=init_managers
	readline.set_completer_delims(' ')
	readline.set_completer(completer)
	readline.parse_and_bind("tab: complete")


def execute(command):
	if command == "login":
		http.login(wrapper.gateway)
		return
	if command in ["quit","exit"]:
		sys.exit()
		return
	level=find_level(command)
	if level < 3 : print 'command is not complete'
	elif level >= 3 and command.split(' ')[2] in db.get_structure(command.split(' ')[0],'command'):
		wrapper.i_command(command)
	elif level >= 4 and command.split(' ')[2] == "get":
		wrapper.i_get(command)
	elif level >= 4 and command.split(' ')[2] == "set":
		wrapper.i_set(command)
	elif level >= 4 and command.split(' ')[2] == "query":
		wrapper.i_query(command)

## get std buffer and decide for best remommendation
## 1st level: managers
## 2nd level: instances of managers
## 3rd level: wherever root array points for commands typically : commands + get + set + query
## 4th ++ levels: wherever the best path is iterated.
## If any recommendation found with % prefix completer gets this value from issuing get command first internally
## and presents the value as as recommendation

def completer(text, state):
	premature=str(readline.get_line_buffer())
	level=find_level(premature)
	if level <= 1:
		complete=managers
	if level == 2:
		complete=wrapper.get_instances(premature.split(' ')[0])
	if level == 3:
		complete=iterator(premature.split(' ')[0],'root',[premature.split(' ')[0]],1)
	if level >= 4:
		path=premature.split(' ')[0:1] + premature.split(' ')[2:-1]
		complete=iterator(premature.split(' ')[0],'root',path,1)
		if len(complete)==1 and complete[0][0]=='%':
			premature=str(readline.get_line_buffer())
			ins=premature.split(' ')[1]
			parameter=complete[0][1:]
			xml="<xmlrequest version=\"1.0.1\">\n<command inst=\"cfgmgr-0\"><key>begin_transaction</key><value>"+ins+"</value></command> <get inst=\""+ins+"\"><key>"+parameter+"</key><value/></get><command inst=\"cfgmgr-0\"><key>end_transaction</key><value>"+ins+"</value></command> </xmlrequest>"
			xml=http.send_xml(xml)
			complete=xml.values()
	options = [x for x in complete if x.startswith(text)]
	try:
		return options[state]+' '
	except IndexError:
		return None

## finds next possibilities for the path in inter pointed arrays:
# instance: manager instance
# lst: which list to start search from the structure array which has instance key
# pre: previus path
# flag: flag for iteration: 1/0


def iterator(instance,lst,pre,flag):
	complete=[]
	try:
		items=db.get_structure(instance,lst)
	except:
		items=[]
	for item in items:
		if flag :
			for item in items:
				if isinstance(item, types.ListType) :
					if len(pre)>1 and (item[0]==pre[0] or item[0][0]=='%') :
						pre.pop(0)
						complete.extend(iterator(instance,item[1],pre,1))
			for item in items:
				if isinstance(item, types.ListType) :
					if len(pre) == 1 and (item[0]==pre[0] or item[0][0]=='%') :
						complete.extend(iterator(instance,item[1],pre,0))
			for item in items:
				if isinstance(item, types.ListType) :
					if len(pre) == 1 and item[0]!=pre[0] :
						break
		if not flag :
			for item in items:
				if isinstance(item, types.ListType):
					complete.append(item[0])
				else:
					complete.append(item)
	complete=list(set(complete))
	return complete

def find_level(command):
	command=command.split(' ')
	return len(command)

